<template>
  <div class="pages inDepotAdd">
    <div>
      <!-- 头部 -->

      <div class="operationBox tableSearch" style=" margin-left:30px;">
        <el-button type="primary" @click="submitForm('formdata')" size="mini">保存</el-button>
        <el-button type="primary" @click="showGoods()" size="mini">添加商品</el-button>
      </div>
      <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
        <el-row>
          <el-col :span="9">
            <el-form-item label="入库仓库：" prop="warehouseId">
              <el-select size="small" style="width:200px" v-model="warehouseId" placeholder="请先选择入库仓库" @change="getwarehouseName">
                <el-option v-for="item in cangArray" :key="item.index" :label="item.repositoryName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据日期：" prop="orderDate">
              <el-date-picker v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据号：">
              <el-input v-model="formdata.purchaseinCode" placeholder="单据号自动生成" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="#" width="55"></el-table-column>
          <el-table-column prop="name" label="商品" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <!-- <el-table-column prop="goodsBatchNumber" label="商品批号" align="center"></el-table-column> -->
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <!-- <el-table-column prop="warehouseName" label="仓库" align="center" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.warehouseName" size="mini" disabled>
                <el-button type="primary" @click="showCang(scope.$index)" slot="append">选择</el-button>
              </el-input>
            </template>
          </el-table-column> -->
          <el-table-column prop="goodsBatchNumber" label="商品批次" align="center" width="150">
            <template slot-scope="scope">
              <template v-if="scope.row.isBatch=='1'">
                <span v-if='scope.row.goodsBatchNumber'>{{scope.row.goodsBatchNumber}}</span>
                <input v-else class="commonInput" v-model="scope.row.goodsBatchNumber" size="mini" type="text" style="width:100px" value="1" min="1" maxlength="8" oninput="value=value.replace(/[\W]/g,'')" onafterpaste="value=value.replace(/[\W]/g,'')">
              </template>
              <template v-if="scope.row.isBatch=='0'">
                 <span>{{"---"}}</span>
              </template>
              <!-- <input v-else class="commonInput" v-model="scope.row.goodsBatchNumber" size="mini" type="text" value="1" min="1" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else if(this.value){this.value=parseInt(this.value.replace(/\D/g,''))}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"> -->
            </template>
          </el-table-column>
          <!-- 集团订单新加功能5/31 -->
          <el-table-column prop="dateInProduced" label="生产日期" align="center" width="100">
             <template slot-scope="scope" >
            <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
            <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
          </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="parameter" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in  scope.row.parameter" :key="index" v-if='item'>
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null">{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.goodsPrice==null ? 0.00 : scope.row.goodsPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsNum" label="数量" align="center" width="150">
            <template slot-scope="scope">
              <input class="commonInput" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="1" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else if(this.value){this.value=parseInt(this.value.replace(/\D/g,''))}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
            </template>
          </el-table-column>
          <el-table-column prop="goodsAmount" label="总价" align="center">
            <template slot-scope="scope">
              <span>{{(Number(scope.row.goodsPrice) * Number(scope.row.goodsNum)).toFixed(2)}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.name" @click="handleCancel(scope.$index)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="th-right">
        <el-form :model="formdata" :rules="rules" label-width="120px" size="mini">
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作员：">
                <el-input v-model="formdata.creater" disabled></el-input>
              </el-form-item>
              <el-form-item label="备注：">
                <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="总计：" prop="priceTotal">
                <el-input v-model="formdataTotal" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 商品选择弹出框 -->
      <el-dialog title="商品选择" class="addshopname" :visible.sync="dialogTableVisible_good" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
        <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="save_good">选择</el-button>
          <el-button size="mini" @click="closes">取消</el-button>
        </div>
        <div class="tableSearch tableSearchs posi">
          <i class="el-input__icon el-icon-search" @click="searchSelect"></i>
          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item label="" label-width="15px">
              <el-input class="input" v-model="selectdatas.keyword" size="small" placeholder="输入商品名称">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="goodArray" stripe border ref="multipleTable" tooltip-effect="dark" @selection-change="changeFun_good">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="name" label="商品" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="goodsBatchNumber" label="商品批号" align="center">
            <template slot-scope="scope" >
            <span v-if="scope.row.isBatch == '1'">{{scope.row.goodsBatchNumber}}</span>
            <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
          </template>
          </el-table-column>
         <!-- 集团订单新加功能5/31 -->
          <el-table-column prop="dateInProduced" label="生产日期" align="center" width="100">
            <template slot-scope="scope" >
             <span v-if="scope.row.isBatch == '1'">{{scope.row.dateInProduced}}</span>
             <span v-if="scope.row.isBatch == '0'">{{"---"}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="parameter" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in  scope.row.parameter" :key="index" v-if="item">
                <span>{{item.paramName}} :</span>
                <span>{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChange_good" @current-change="handleCurrentChange_good" :current-page="currentpage_good" :page-sizes="[20,40]" :page-size="pageSize_good" layout="total, sizes, prev, pager, next, jumper" :total="total_good">
          </el-pagination>
        </div>
      </el-dialog>
      <!-- 仓库选择弹出框 -->
      <!-- <el-dialog title="仓库选择" class="addshopname" :visible.sync="dialogTableVisible_cang" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
        <i class="el-icon-close icon" @click="dialogTableVisible_cang=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="save_cang">选择</el-button>
          <el-button size="mini" @click="dialogTableVisible_cang=false">取消</el-button>
          <el-alert title="未录入期初库存仓库不可选择" type="warning">
          </el-alert>
        </div>
        <el-table :data="cangArray" ref="multipleTable" border tooltip-effect="dark" highlight-current-row @selection-change="changeFun_cang">
          <el-table-column type="selection" :selectable='checkboxInit' width="55"></el-table-column>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="repositoryName" label="仓库" align="center"></el-table-column>
          <el-table-column prop="repositoryAddress" label="地址" align="center"></el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChange_cang" @current-change="handleCurrentChange_cang" :current-page="currentpage_cang" :page-sizes="[20,30]" :page-size="pageSize_cang" layout="total, sizes, prev, pager, next, jumper" :total="total_cang">
          </el-pagination>
        </div>
      </el-dialog> -->
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import sdInput from "@/components/SdInput";
// import breadcrumb from '@components/path'
import u from "@/util";
import {
  //   storeDownList,
  saveOrUpdateInBound,
  getRepositoryListPage,
  findGoodsRepositoryByRepositoryId,
  addRepertoryInBound
} from "@/api";
export default {
  components: { sdInput },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      linkName: state => state.linkName,
      userInfo: state => state.userInfo,
      mobile: state => state.mobile,
      userId: state => state.userId,
      }),
    formdataTotal: function() {
      let totalPrice = 0;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsAmount =
          this.tableData[i].goodsPrice * this.tableData[i].goodsNum;
        totalPrice += this.tableData[i].goodsPrice * this.tableData[i].goodsNum;
      }
      this.formdata.purchaseAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    }
  },
  data() {
    return {
      warehouseId: "",
      warehouseName: "",
      selectGoods: [],
      options: [],
      //商品输入框
      selectdata: {
        keyword: "",
        barCode: ""
      },
      selectdatas: {
        keyword: "",
        barCode: ""
      },
      consignee: "",
      linkman: "",
      address: "",
      tableData: [],
      //新增表单
      formdata: {
        inCode: "",
        warehouseName: "",
        warehouseId: "",
        orderDate: "",
        creater: "",
        remark: "",
        inAmount: "",
        purchaseinCode: ""
      },
      selection_cang: {},
      dialogTableVisible_good: false,
      dialogTableVisible_cang: false,
      selection_good: [],
      goodArray: [],
      cangArray: [],
      pageSize_good: 20,
      pageSize_cang: 20,
      currentpage_good: 1,
      currentpage_cang: 1,
      total_good: 0,
      total_cang: 0,
      rules: {
        orderDate: [
          { required: true, message: "请选择入库时间", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.init();
    this.data();
    this.getCang();
  },
  methods: {
    getwarehouseName(val) {
      this.cangArray.forEach(ele => {
        if (ele.id == val) {
          this.warehouseName = ele.repositoryName;
          if (ele.openingInventoryState == 0) {
            this.$message({
              type: "error",
              message: "该仓库未录入期初库存"
            });
            this.warehouseId = "";
          }
        }
      });
    },
    numall: u.numall,
    searchSelect() {
      this.selectdata.keyword = this.selectdatas.keyword;
      this.selectdata.barCode = this.selectdatas.barCode;
       this.currentpage_good=1
      this.getGoods(this.pageSize_good, this.currentpage_good);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },
    checkboxInit(row, index) {
      if (row.openingInventoryState == 0) {
        return 0;
      } else {
        return 1;
      }
    },
    //--------默认当前时间
    data(picker) {
      new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10);
      const date = new Date();
      var datas = date.setTime(date.getTime());
      var datase = u.foryear(parseInt(datas));
      this.formdata.orderDate = datase;
    },
    //默认当前操作员
    init() {
      if (this.linkName != undefined&&this.linkName != "") {
        this.formdata.creater = this.linkName;
      } else {
        this.formdata.creater = this.mobile;
      }
      // this.tableData.push([{ id: '' }])
    },
    getGoods(pageSize, pageNum) {
      let data = {
        goodsName: this.selectdata.keyword,
        pageSize: pageSize,
        pageNum: pageNum,
        shopId: this.merchantId,
        barCode: this.selectdata.barCode,
        status: 0,
        repositoryId: this.warehouseId
      };
      if (
        this.warehouseId == "" ||
        this.warehouseId == undefined ||
        this.warehouseId == null
      ) {
        this.$message({
          type: "error",
          message: "请选择入库仓库"
        });
      } else {
        findGoodsRepositoryByRepositoryId(data).then(res => {
          res.data.list.forEach(element => {
            element.goodsNum = "0";
            element.warehouseName = "";
            //element.goodsBatchNumber=""
          });
          this.dialogTableVisible_good = true;
          this.goodArray = res.data.list;
          this.total_good = res.data.pageTotal;
        });
      }
    },
    showGoods() {
      this.getGoods(this.pageSize_good, this.currentpage_good);
    },
    showCang(index) {
      this.cang_index = index;
      this.dialogTableVisible_cang = true;
      this.getCang(this.pageSize_cang, 1);
    },
    closes() {
      this.dialogTableVisible_good = false;
      this.$refs.multipleTable.clearSelection();
      this.goodArray = [];
    },
    save_cang() {
      let i = this.cang_index;
      this.tableData[i].warehouseName = this.selection_cang.repositoryName;
      this.tableData[i].warehouseId = this.selection_cang.id;
      this.dialogTableVisible_cang = false;
    },
    // changeFun_cang(val) {
    //   if (val) {
    //     this.selection_cang = val;
    //   } else {
    //     this.selection_cang = {};
    //   }
    // },
    changeFun_cang(val) {
      let active = {};
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection();
        active = val.pop();
        this.$refs.multipleTable.toggleRowSelection(active);
        this.selection_cang = active;
      } else {
        this.selection_cang = val[0];
      }
    },
    //-----------仓库列表
    getCang(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        pageNum: pageNum,
        nameCode: "",
        shopId: this.merchantId,
        status:"0"
      };
      getRepositoryListPage(data).then(res => {
        this.cangArray = res.data.list;
        this.total_cang = res.data.pageTotal;
      });
    },
    // ------点击返回按钮
    goBack() {
      window.history.go(-1);
    },
    //---------新增保存
    handleSave() {
      let sendPost = true;
      if (this.tableData.length == 0) {
        sendPost = false;
        this.$message({
          type: "error",
          message: "请刷新页面，选择商品"
        });
        return false;
      }
      this.tableData.forEach(element => {
        element.goodsId = element.id;
        element.goodsName = element.name;
        element.goodsOrganizationSkuId = element.id;
        element.goodsSpec = element.parameter;
        //element.goodsBatchNumber = element.goodsBatchNumber;
        (element.warehouseId = this.warehouseId),
          (element.warehouseName = this.warehouseName);
        if (
          element.isBatch == 1 &&
          (element.goodsBatchNumber == "" ||
            element.goodsBatchNumber == null ||
            element.goodsBatchNumber == undefined)
        ) {
          sendPost = false;
          this.$message({
            type: "error",
            message: "请录入商品批次"
          });
          return false;
        }
        if (element.goodsNum <= 0 && element.goodsNum != "") {
          sendPost = false;
          this.$message({
            type: "error",
            message: "商品数量不能小于等于0"
          });
          return false;
        }
      });
      if (sendPost == true) {
        let Datas = {
          shopId: this.merchantId,
          orderDate: this.formdata.orderDate,
          creater: this.userId,
          inAmount: this.formdataTotal,
          remark: this.formdata.remark,
          inType: 2,
          goodsList: JSON.stringify(this.tableData)
        };
        addRepertoryInBound(Datas).then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            u.routerTo("/order-center/stock-management/stock-inDepotMg");
          } 
        });
      }
    },
    save_good() {
      if (this.selection_good.length === 0) {
        this.$message({
          type: "error",
          message: "请先选择商品!"
        });
      } else {
        this.tableData = this.tableData.concat(this.selection_good);
        // this.tableData.forEach(item=>{
        //   item.goodsBatchNumber=''
        // })
        this.closes();
      }
    },
    uniq(arr) {
      let newArr = [arr[0]];
      for (let i = 1; i < arr.length; i++) {
        let repeat = false;
        for (let j = 0; j < newArr.length; j++) {
          if (
            arr[i].id === newArr[j].id &&
            arr[i].isBatch == "0" &&
            newArr[j].isBatch == "0"
          ) {
            repeat = true;
            break;
          } else {
          }
        }
        if (!repeat) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    changeFun_good(val) {
      if (val) {
        this.selection_good = val;
      } else {
        this.selection_good = [];
      }
    },
    handleCancel(index) {
      this.tableData.splice(index, 1);
    },
    handleSizeChange_good(val) {
      this.pageSize_good = val;
      this.currentpage_good=1
      this.getGoods(val, this.currentpage_good);
    },
    handleCurrentChange_good(val) {
      this.currentpage_good=val;
      this.getGoods(this.pageSize_good, val);
    },
    handleSizeChange_cang(val) {
      this.pageSize_cang = val;
      this.currentpage_cang=1;
      this.getCang(val, this.currentpage_cang);
    },
    handleCurrentChange_cang(val) {
      this.currentpage_cang = val;
      this.getCang(this.pageSize_cang, val);
    }
  }
};
</script>
<style scoped>
.th-right {
  width: 50%;
  min-width: 300px;
  float: right;
  margin-top: 20px;
}
.tableSearchs {
  position: relative;
}
.tableSearchs .el-input__icon {
  position: absolute;
  top: 12px;
  left: 190px;
  z-index: 10;
  width: 25px;
  height: 35px;
}
.posi {
  display: block;
  float: left;
}
.operationBox {
  text-align: left;
}
</style>
<style lang="less" scoped>
thead {
  .el-table-column--selection {
    .cell {
      display: none;
    }
  }
}
</style>

<style>
.el-input__inner {
  padding: 0 20px;
}
</style>


